<template>
    <ContentWrap>
        <el-table :data="memberData">
            <el-table-column label="年级" align="center" prop="grade">
                <template #default="scope">
                    {{ getGradeLabel(scope.row.grade) }}
                </template>
            </el-table-column>
            <el-table-column label="学生总数" align="center" prop="memberCount"/>
            <el-table-column label="专业数量" align="center" prop="majorCount"/>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button
                        link
                        type="primary"
                        @click="openDeatilForm(scope.row.grade)"
                    >
                        查看
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
    </ContentWrap>

    <el-dialog title="专业分布" v-model="dialogZYFBVisible" draggable destroy-on-close>
        <el-table :data="ZYFBData" height="360px">
            <el-table-column label="专业" align="center" prop="majorName"/>
            <el-table-column label="专业人数" align="center" prop="memberCount"/>
        </el-table>

        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="closeZYFB">确 定</el-button>
            </span>
        </template>
    </el-dialog>

    <ContentWrap>
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px"
                 label-width="70px" @submit.native.prevent>
            <el-form-item label="归属学校" prop="schoolId" v-if="tenantId == 1">
                <el-select v-model="queryParams.schoolId" placeholder="请选择" class="!w-240px" filterable default-first-option clearable>
                    <el-option v-for="item in schools" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学生学号" prop="code">
                <el-input v-model="queryParams.code" class="!w-240px" clearable
                          placeholder="请输入学生学号" @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="学生姓名" prop="name">
                <el-input v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入名称"
                          @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="queryParams.mobile" class="!w-240px" clearable placeholder="请输入手机号"
                          @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="专业" prop="majorId">
                <el-select v-model="queryParams.majorId" placeholder="请选择专业" clearable>
                    <el-option v-for="item in majors" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="当前年级" prop="grade">
                <el-select v-model="queryParams.grade" placeholder="请选择年级" clearable>
                    <el-option v-for="item in grades" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="学期" prop="term">
                <el-select v-model="queryParams.term" placeholder="请选择学期" clearable>
                    <el-option v-for="item in terms" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="班级" prop="className">
              <el-input v-model="queryParams.className" class="!w-240px" clearable placeholder="请输入班级"
                        @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item label="预约状态" prop="canSub">
                <el-select v-model="queryParams.canSub" placeholder="请选择预约状态" clearable>
                    <el-option v-for="item in canSubs" :label="item.name" :value="item.id"/>
                </el-select>
            </el-form-item>
            <el-form-item label="定位权限" prop="canLocation">
              <el-select v-model="queryParams.canLocation" placeholder="请选择定位状态" clearable>
                <el-option v-for="item in canLocations" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="handleQuery">
                    <Icon class="mr-5px" icon="ep:search"/>
                    搜索
                </el-button>
                <el-button @click="resetQuery">
                    <Icon class="mr-5px" icon="ep:refresh"/>
                    重置
                </el-button>
                <el-button v-hasPermi="['yxt:member:create']" plain type="primary"
                           @click="openForm('create')">
                    <Icon class="mr-5px" icon="ep:plus"/>
                    新增
                </el-button>
                <el-button type="warning" plain @click="handleImport" v-hasPermi="['yxt:member:import']">
                    <Icon icon="ep:upload"/>
                    导入
                </el-button>
                <el-button type="success" plain @click="handleExport" :loading="exportLoading"
                           v-hasPermi="['yxt:member:export']">
                    <Icon icon="ep:download"/>
                    导出
                </el-button>
                <el-button type="success" plain @click="openSxrq" v-hasPermi="['yxt:member:import']">
                    <Icon icon="ep:setting"/>
                    升学日期
                </el-button>
                <el-button type="primary" plain @click="router.push('studentCourseData')" v-hasPermi="['yxt:member:course:data']">
                  <Icon icon="ep:reading"/>
                  查看学生总课程数据
                </el-button>
            </el-form-item>
        </el-form>
    </ContentWrap>

    <el-dialog title="升学日期" v-model="dialogFormVisible" width="420px" draggable>
        <el-form :model="sxform" :rules="formRules" label-width="120px">
            <el-form-item label="上学期升学日期">
                <el-input v-model="sxform.sxqDate" class="!w-240px" clearable
                          placeholder="请输入上学期升学日期格式 09-01"/>
            </el-form-item>
            <el-form-item label="下学期升学日期">
                <el-input v-model="sxform.xxqDate" class="!w-240px" clearable
                          placeholder="请输入下学期升学日期格式 02-01"/>
            </el-form-item>
            <el-form-item label="毕业日期">
                <el-input v-model="sxform.byDate" class="!w-240px" clearable
                          placeholder="请输入毕业时间日期格式 06-01"/>
            </el-form-item>
        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="closeSxrq">取 消</el-button>
      <el-button type="primary" @click="updateSXRQ">确 定</el-button>
    </span>
        </template>
    </el-dialog>

    <ContentWrap>
        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="学生学号" prop="code" min-width="120"/>
            <el-table-column label="学生姓名" prop="name" min-width="100"/>
            <el-table-column label="头像" prop="avatar" width="50">
                <template #default="scope">
                    <div style="width: 36px; height: 36px">
                        <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"
                                  preview-teleported hide-on-click-modal/>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="手机号" prop="mobile" min-width="120"/>
            <el-table-column label="归属学校" prop="schoolName"/>
            <el-table-column label="当前年级" prop="grade">
                <template #default="scope">
                    {{ getTermLabel(scope.row.grade, scope.row.term) }}
                </template>
            </el-table-column>
            <el-table-column label="班级" prop="className"/>
            <el-table-column label="专业" prop="majors" min-width="200">
                <template #default="scope">
                    <el-tag v-for="tag in scope.row.majors" type="warning" :key="tag"
                            :disable-transitions="true" class="mr-5px">
                        {{ tag.name }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="乐器" prop="musical" min-width="200"/>
            <el-table-column label="类型" prop="type">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_USER_TYPE" :value="scope.row.type"/>
                </template>
            </el-table-column>
            <el-table-column label="性别" prop="sex">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="scope.row.sex"/>
                </template>
            </el-table-column>
            <el-table-column label="状态" prop="status">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.YXT_ACTIVE_STATUS" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="预约权限" prop="canSub">
                <template #default="scope">
                    <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.canSub"/>
                </template>
            </el-table-column>
            <el-table-column label="定位权限" prop="canLocation">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.canLocation"/>
              </template>
            </el-table-column>
            <el-table-column label="本学期练琴时长" prop="totalDuration" min-width="200"/>
            <el-table-column label="本学期爽约次数" prop="brokenCount" min-width="200"/>
            <el-table-column label="本学期取消次数" prop="cancelCount" min-width="200"/>
            <el-table-column :formatter="dateFormatter" align="center" label="创建时间" prop="createTime"
                             width="180"/>
            <el-table-column :width="160" align="center" label="操作" fixed="right">
                <template #default="scope">
                    <el-button link type="primary" @click="() => router.push('detail/'+scope.row.id)">
                        查看
                    </el-button>
                    <el-button v-hasPermi="['yxt:member:update']" link type="primary"
                               @click="openForm('update', scope.row.id)">
                        编辑
                    </el-button>
                    <el-button v-hasPermi="['yxt:member:delete']" link type="danger"
                               @click="handleDelete(scope.row.id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo"
                    :total="total" @pagination="getList"/>
    </ContentWrap>

    <MemberForm ref="formRef" @success="getList"/>
    <MemberImportForm ref="importFormRef" @success="getList"/>
</template>

<script lang="ts" setup>
import {DICT_TYPE} from '@/utils/dict'
import {dateFormatter} from '@/utils/formatTime'
import {useMemberApi} from "@/api/yxt/member";
import MemberForm from "@/views/yxt/member/student/MemberForm.vue";
import {useMajorApi} from "@/api/yxt/major";
import {useConfirm, useMessage} from "@/components/Notice";
import router from "@/router";
import {useConfigApi} from "@/api/yxt/config";
import * as XLSX from 'xlsx';
import MemberImportForm from "@/views/yxt/member/student/MemberImportForm.vue";
import {getTenantId} from "@/utils/auth";
import {useSchoolApi} from "@/api/yxt/school";

defineOptions({name: 'YxtStudentMember'})

const tenantId = getTenantId();

const majorApi = useMajorApi();
const memberApi = useMemberApi();
const schoolApi = useSchoolApi();
const {t} = useI18n() // 国际化

const dialogZYFBVisible = ref(false) //专业分布
const dialogFormVisible = ref(false) //升学时间设置
const memberData = ref([])  //数据汇总
const sxform = ref({
    sxqDate: "",
    xxqDate: "",
    byDate: ""
}) //时间选择
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const grades = ref([
    {name: "大一", id: 1},
    {name: "大二", id: 2},
    {name: "大三", id: 3},
    {name: "大四", id: 4},
    {name: "已毕业", id: 5}
])
const terms = ref([
    {name: "上学期", id: 1},
    {name: "下学期", id: 2},
])
const canSubs = ref([
    {name: "可预约", id: 0},
    {name: "不可预约", id: 1}
])
const canLocations = ref([
  {name: "开启", id: 0},
  {name: "关闭", id: 1}
])
const queryParams = reactive({
    memberType: 0,
    pageNo: 1,
    pageSize: 10,
    schoolId: '',
    name: '',
    grade: undefined,
    term: undefined,
    className: undefined,
    code: '',
    mobile: '',
    canSub: undefined,
    canLocation: undefined,
    majorId: undefined,
})
const queryFormRef = ref()
const majors = ref<Array<any>>([])
const schools = ref<Array<any>>([])
const multipleSelection = ref<Array<any>>([])
const ZYFBData = ref<Array<any>>([])

const formRules = reactive({
    sxqDate: [{required: true, message: '上学期日期不能为空', trigger: ['blur', 'change']}],
    xxqDate: [{required: true, message: '下学期日期不能为空', trigger: ['blur', 'change']}],
    byDate: [{required: true, message: '毕业日期不能为空', trigger: ['blur', 'change']}],
})

const getList = async () => {
    loading.value = true
    try {
        const data = await memberApi.getMemberPage(queryParams)
        list.value = data.list
        total.value = data.total
    } finally {
        loading.value = false
    }
}

function getGradeLabel(grade) {
    // 根据 grade 和 term 生成学期标签
    let gradeLabel = '';
    switch (grade) {
        case 0:
            gradeLabel = "全部";
            break;
        case 1:
            gradeLabel = '大一';
            break;
        case 2:
            gradeLabel = '大二';
            break;
        case 3:
            gradeLabel = '大三';
            break;
        case 4:
            gradeLabel = '大四';
            break;
        default:
            gradeLabel = '已毕业';
    }
    return gradeLabel;
}

function getTermLabel(grade, term) {
    // 根据 grade 和 term 生成学期标签
    let gradeLabel = '';
    switch (grade) {
        case 1:
            gradeLabel = '大一';
            break;
        case 2:
            gradeLabel = '大二';
            break;
        case 3:
            gradeLabel = '大三';
            break;
        case 4:
            gradeLabel = '大四';
            break;
        case 5:
            gradeLabel = '已毕业';
            break;
        default:
            gradeLabel = '已毕业';
    }
    if (grade == 5) return gradeLabel;
    let termLabel = '';
    switch (term) {
        case 1:
            termLabel = '(上)';
            break;
        case 2:
            termLabel = '(下)';
            break;
        default:
            termLabel = '';
    }
    return gradeLabel + termLabel;
}

const openDeatilForm = async (grade) => {
    dialogZYFBVisible.value = true;
    ZYFBData.value = await memberApi.majorMemberCount({
        memberType: 0,
        grade: grade
    })

}

const closeZYFB = async () => {
    dialogZYFBVisible.value = false;
}

const openSxrq = async () => {
    dialogFormVisible.value = true;
    sxform.value = await useConfigApi().getSxRq()
}

const closeSxrq = async () => {
    dialogFormVisible.value = false;
    sxform.value = {
        sxqDate: '',
        xxqDate: '',
        byDate: ''
    }
}
const updateSXRQ = async () => {
    dialogFormVisible.value = false;
    useConfirm(t("common.updateMessage"), async () => {
        await useConfigApi().setSxRq(sxform.value).finally(() => useMessage(t('common.updateSuccess')));
    });
}
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
}
const handleQuery = () => {
    queryParams.pageNo = 1
    getList()
}

const resetQuery = () => {
    queryFormRef.value.resetFields()
    handleQuery()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
    formRef.value.open(type, id)
}

const handleDelete = (id: number) => {
    useConfirm(t("common.delMessage"), async () => {
        await memberApi.deleteStu(id);
        getList().finally(() => useMessage(t('common.delSuccess')));
    });
}

const importFormRef = ref()
const handleImport = () => {
    importFormRef.value.open()
}

const exportLoading = ref(false)
const handleExport = () => {
    useConfirm(t("common.exportMessage"), async () => {
        exportLoading.value = true
        try {
            if (list.value.length == 0) {
                useMessage("没有可导出数据", "warning")
                return;
            }
            const exportData = multipleSelection.value.length > 0 ? multipleSelection.value
                : await memberApi.listNoPage(queryParams);
            const formData = exportData.map(formatData)
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet(formData);
            // 将工作表添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "选中数据");
            // 生成文件
            XLSX.writeFile(wb, "学生数据.xlsx");
        } finally {
            exportLoading.value = false
        }
    });
}

const formatData = (item: any) => {
    return {
        "学生学号": item.code,
        "名称": item.name,
        // "头像": item.avatar,
        "手机号": item.mobile,
        "归属学校": item.schoolName,
        "当前年级": getTermLabel(item.grade, item.term),
        "班级": item.className,
        "专业": item.majors.map(major => major.name).join(","),
        "乐器": item.musical,
        "类型": item.type == 0 ? "学生" : "教师",
        "性别": item.sex == 1 ? "男" : "女",
        "状态": item.status == 1 ? "冻结" : "激活",
        "预约权限": item.canSub == 0 ? "开启" : "关闭",
        "本学期练琴时长": item.totalDuration,
        "本学期爽约次数": item.brokenCount,
        "本学期取消次数": item.cancelCount,
        "创建时间": formatDateTime(item.createTime)
    }
}

//时间戳转换时间
const formatDateTime = (timestamp: any) => {
// 使用 Intl.DateTimeFormat 格式化日期时间
    const formattedDate = new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false, // 使用 24 小时制
    }).format(new Date(timestamp));
    return formattedDate;
}

onMounted(async () => {
    await getList();
    memberData.value = await memberApi.memberData({memberType: 0})
    majors.value = await majorApi.getMajorList();
    schools.value = await schoolApi.getSimpleList();
})
</script>
